/**
 * 排班系统初始化数据
 */

const mongoose = require('./model/db');
const Technician = require('./model/Technician');
const Schedule = require('./model/Schedule');
const { User, Role } = require('./model/model');

async function initScheduleData() {
  try {
    // 确保数据库连接
    await mongoose.connection.once('open', () => {
      console.log('数据库连接成功');
    });

    // 检查是否已有数据
    const technicianCount = await Technician.countDocuments();
    if (technicianCount > 0) {
      console.log('已有技师数据，跳过初始化');
      return;
    }

    // 创建员工角色
    let employeeRole = await Role.findOne({ name: '员工' });
    if (!employeeRole) {
      employeeRole = new Role({
        name: '员工',
        description: '普通员工',
        permissions: ['view_schedule', 'view_own_schedule']
      });
      await employeeRole.save();
      console.log('创建员工角色');
    }

    // 创建测试技师数据
    const testTechnicians = [
      {
        username: '张技师',
        password: '123456',
        email: 'zhang@example.com',
        phone: '13800138001',
        sex: '男',
        age: 28,
        role: employeeRole._id,
        avatar: '',
        rating: 4.8,
        totalRatings: 156,
        workStatus: '空闲中',
        skills: ['面部护理', '身体按摩', 'SPA'],
        experience: 5
      },
      {
        username: '李技师',
        password: '123456',
        email: 'li@example.com',
        phone: '13800138002',
        sex: '女',
        age: 25,
        role: employeeRole._id,
        avatar: '',
        rating: 4.9,
        totalRatings: 203,
        workStatus: '空闲中',
        skills: ['美甲', '美发', '面部护理'],
        experience: 3
      },
      {
        username: '王技师',
        password: '123456',
        email: 'wang@example.com',
        phone: '13800138003',
        sex: '男',
        age: 32,
        role: employeeRole._id,
        avatar: '',
        rating: 4.7,
        totalRatings: 89,
        workStatus: '休息中',
        skills: ['足疗', '身体按摩', 'SPA'],
        experience: 8
      },
      {
        username: '赵技师',
        password: '123456',
        email: 'zhao@example.com',
        phone: '13800138004',
        sex: '女',
        age: 26,
        role: employeeRole._id,
        avatar: '',
        rating: 4.6,
        totalRatings: 134,
        workStatus: '空闲中',
        skills: ['美甲', '美发'],
        experience: 4
      }
    ];

    const createdTechnicians = [];
    for (const techData of testTechnicians) {
      const technician = new Technician(techData);
      await technician.save();
      createdTechnicians.push(technician);
    }

    console.log(`创建了 ${createdTechnicians.length} 个测试技师`);

    // 创建测试排班数据
    const today = new Date();
    const testSchedules = [];

    // 为每个技师创建未来7天的排班
    for (let i = 0; i < 7; i++) {
      const date = new Date(today);
      date.setDate(today.getDate() + i);

      // 每天安排2-3个技师
      const dailyTechnicians = createdTechnicians.slice(0, 2 + Math.floor(Math.random() * 2));
      
      for (const tech of dailyTechnicians) {
        const startHour = 9 + Math.floor(Math.random() * 6); // 9:00-15:00
        const endHour = startHour + 4 + Math.floor(Math.random() * 4); // 工作4-8小时

        const start = new Date(date);
        start.setHours(startHour, 0, 0, 0);
        
        const end = new Date(date);
        end.setHours(endHour, 0, 0, 0);

        const schedule = new Schedule({
          technician: tech._id,
          title: `${tech.username}的工作安排`,
          start: start,
          end: end,
          color: `hsl(${Math.random() * 360}, 70%, 60%)`,
          notes: `今日工作安排：${tech.skills.join('、')}`,
          createdBy: (await User.findOne())?._id || new mongoose.Types.ObjectId()
        });

        testSchedules.push(schedule);
      }
    }

    for (const schedule of testSchedules) {
      await schedule.save();
    }

    console.log(`创建了 ${testSchedules.length} 个测试排班`);
    console.log('排班系统初始化数据完成');

  } catch (error) {
    console.error('初始化数据失败:', error);
  } finally {
    mongoose.connection.close();
  }
}

// 如果直接运行此文件
if (require.main === module) {
  initScheduleData();
}

module.exports = initScheduleData;